package com.zrrd.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.zrrd.common.aliyun.GreenImageScan;
import com.zrrd.common.aliyun.GreenTextScan;
import com.zrrd.common.exception.CustomException;
import com.zrrd.feign.apis.IArticleClient;
import com.zrrd.file.service.FileStorageService;
import com.zrrd.model.article.dtos.ArticleDto;
import com.zrrd.model.common.dtos.ResponseResult;
import com.zrrd.model.common.enums.AppHttpCodeEnum;
import com.zrrd.model.wemedia.pojos.WmChannel;
import com.zrrd.model.wemedia.pojos.WmNews;
import com.zrrd.model.wemedia.pojos.WmUser;
import com.zrrd.wemedia.mapper.WmChannelMapper;
import com.zrrd.wemedia.mapper.WmNewsMapper;
import com.zrrd.wemedia.mapper.WmUserMapper;
import com.zrrd.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WanJl
 * @version 1.0
 * @title WmNewsAutoScanServiceImpl
 * @description
 * @create 2023/9/26 10:03
 */
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 自媒体新闻审核
     *
     * @param id 自媒体新闻id
     */
    @Override
    @Async//异步调用该方法
    public void autoScanWmNews(Integer id) {

        //1.查询自媒体新闻
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl--新闻不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //1.提取新闻内容，分别获取新闻的文字和图片
            Map<String, Object> map = handleTextAndImages(wmNews);
            //2.审核文本内容 调用阿里云接口
            boolean isTextScan = handleTextScan((String) map.get("content"), wmNews);
            //3.审核图片内容 调用阿里云接口
            List<String> images = (List<String>) map.get("images");
            boolean isImagesScan = handleImagesScan(images, wmNews);

            //4.审核成功，保存APP端相关的新闻数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            //判断，如果responseResult的code不是200，说明保存没成功
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl--文字审核完毕，保存APP端相关的新闻失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            //修改自媒体端新闻内容
            updateWmNews(wmNews, (short) 9, "审核成功");

            //全部完成之后删除图片
            for (String imageUrl:images){
                int i = imageUrl.lastIndexOf("/");
                String image = imageUrl.substring(i);
                image="src/main/resources/tempImages"+image;
                fileStorageService.deleteLoadFile(image);
            }
        }
    }

    /**
     * 修改自媒体服务端新闻信息，
     * 回填article_id、status、reason
     *
     * @param wmNews 回填article_id
     * @param status 设置status=9
     * @param reason 设置reason=审核成功
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient articleClient;
    /**
     * 保存APP端相关的新闻数据的方法
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //copy属性
        BeanUtils.copyProperties(wmNews,dto);
        //新闻布局方式
        dto.setLayout(wmNews.getType());
        //新闻所属频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        //作者id
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        //设置文章id
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }

        //创建时间
        dto.setCreatedTime(new Date());

        //远程服务调用，调用feign-api中的IArticleClient服务接口
        ResponseResult responseResult = articleClient.saveArticle(dto);

        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 审核图片内容
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images == null || images.size() == 0) {
            return flag;
        }
        //下载图片 从minIO下载
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<String> loadImages = new ArrayList<>();

        for (String image : images) {
            String imagePath = fileStorageService.downLoadImage(image, "src/main/resources/tempImages");
            loadImages.add(imagePath);
        }
        try {
            //审核图片 上传本地图片进行审核
            for (String image : loadImages) {
                Map map = greenImageScan.imageScan(image);
                if (map!=null){
                    //判断审核失败的情况
                    if (!map.get("label").equals("nonLabel")){
                        if ((double)map.get("confidence")>30){
                            flag=false;
                            updateWmNews(wmNews,(short)2,"当前新闻中存在违规内容");
                        }else {
                            flag=false;
                            updateWmNews(wmNews,(short)3,"当前新闻中存在不确定内容");
                        }
                    }
                }

            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }

        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核文字内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        content = wmNews.getTitle() + "-" + content;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null) {
                //审核结果是有违规
                if (map.get("labels") != null && map.get("reason") != null) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前新闻中存在违规内容");
                }
            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 提取新闻中的纯文本和图片
     * 1、从自媒体新闻中提取文本
     * 2、从自媒体新闻中提取图片
     * 3、封装到map集合中
     * wmNews.getContent()方法返回的应该是是一个JSON数组，我们要把数组抓换成List<Map>
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //存储图片的集合
        List<String> images = new ArrayList<>();
        //存储文本内容的可增长字符串
        StringBuilder texts = new StringBuilder();
        //1.从自媒体新闻的内容中提取文字和图片
        //判断内容是否为空
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            //把json字符串转换成List<Map>集合
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                //抽取文本
                if (map.get("type").equals("text")) {
                    texts.append(map.get("value"));
                }
                //抽取图片
                if (map.get("type").equals("image")) {
                    images.add((String) map.get("value"));
                }
            }
        }
        //2.提取新闻封面的图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        //把文字和图片分别存入到map集合中
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", texts.toString());
        resultMap.put("images", images);
        return resultMap;
    }

}
